package com.pxxy.springmvc.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/******************
 * @Author yejf
 * @Description TODO
 */
@Configuration
@EnableAspectJAutoProxy //开启AOP
@EnableTransactionManagement //开启申明式事务
@PropertySource("classpath:db.properties") //读取 属性文件
@ComponentScan("com.pxxy.springmvc.service")  //扫描业务层
@MapperScan(basePackages = "com.pxxy.springmvc.mapper")  //扫描mapper
public class AppConfig {

    @Autowired
    private Environment env;   //此类来承载 db.properties文件中的属性

    @Bean
    public DataSource dataSource() {
        //使中 druid 连接池
        DruidDataSource dataSource = new DruidDataSource();
        //设置属性
        dataSource.setUrl(env.getProperty("url"));
        dataSource.setDriverClassName(env.getProperty("driver"));
        dataSource.setUsername(env.getProperty("user"));
        dataSource.setPassword(env.getProperty("password"));
        //
        return dataSource;
    }

    @Bean
    public PlatformTransactionManager transactionManager(@Autowired DataSource dataSource) {
        // 采用 数据源事务管理器[适用于 jdbc和mybatis 技术]
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(@Autowired  DataSource dataSource) throws Exception {
        //创建 由 mybatis-spring 组件提供的 SqlSessoinFactoryBean 对象
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        //设置 数据源 和配置文件的位置
        bean.setDataSource(dataSource);
        //读取配置文件
        bean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
        //
        //bean.setTypeAliasesPackage("com.pxxy.springmvc.entity");
        //返回
        return bean.getObject();
    }

    //以下的配置比较 罗嗦，建议使用 @MapperScan 注解来代替
    /*@Bean
    public AccountMapper accountMapper(@Autowired SqlSessionFactory sqlSessionFactory) {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
        //
        return template.getMapper(AccountMapper.class);
    }

    @Bean
    public UserMapper userMapper(@Autowired SqlSessionFactory sqlSessionFactory) {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
        //
        return template.getMapper(UserMapper.class);
    }*/
}
